<script>
import { version } from '/package.json'
import { appName } from '@/configs/index'
import { getCaptcha, getEmailCaptcha, getSmsCaptcha } from '@/api/user/index'

export default {
  data() {
    return {
      appName,
      version,
      agreed: false,
      loginCode: '',
      memberModel: {
        memberInfo: {
          username: '',
          password: '',
          captcha: '',
          captchaId: '',
        },
      },
      loginTypeList: [
        {
          name: '普通',
          disabled: false,
        },
        {
          name: '手机',
          disabled: false,
        },
        {
          name: '邮箱',
          disabled: false,
        },
      ],
      loginType: '普通',
      imgSrc: '',
      rules: {
        'memberInfo.username': {
          type: 'string',
          required: true,
          message: '请输入内容',
          trigger: ['blur', 'change'],
        },
        'memberInfo.password': {
          type: 'string',
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change'],
        },
        'memberInfo.captcha': {
          type: 'string',
          required: true,
          len: 5,
          message: '请输入5位验证码',
          trigger: ['blur', 'change'],
        },
      },
      tips: '',
    }
  },
  computed: {
    getPlaceholder() {
      if (this.loginType == '手机') {
        return '请输入手机号'
      }
      else if (this.loginType == '邮箱') {
        return '请输入邮箱'
      }
      else {
        return '请输入账号'
      }
    },
  },
  onShow() {
    this.getCaptchaData()
  },
  methods: {
    codeChange(text) {
      this.tips = text
    },
    async getCode() {
      if (this.$refs.uCode.canGetCode) {
        uni.showLoading({
          title: '正在获取验证码',
        })

        if (this.loginType === '手机') {
          const result = await getSmsCaptcha({ phoneNumber: this.memberModel.memberInfo.username })
          if (result.ok) {
            uni.hideLoading()
            uni.$u.toast('验证码已发送')
            this.$refs.uCode.start()
          }
        }
        else if (this.loginType === '邮箱') {
          const result = await getEmailCaptcha({ email: this.memberModel.memberInfo.username })
          if (result.ok) {
            uni.hideLoading()
            uni.$u.toast('验证码已发送')
            this.$refs.uCode.start()
          }
        }
      }
    },
    async getCaptchaData() {
      const result = await getCaptcha()
      if (result.ok) {
        this.imgSrc = result.data.imgPath
        this.memberModel.memberInfo.captchaId = result.data.captchaId
      }
    },
    async handleLogin({ detail = {} } = {}) {
      if (this.loginType == '普通') {
        this.$refs.uForm.validateField('memberInfo.username')
        this.$refs.uForm.validateField('memberInfo.captcha')
        this.$refs.uForm.validateField('memberInfo.password')
        if (this.memberModel.memberInfo.username == '' || this.memberModel.memberInfo.username == '') {
          return
        }

        await this.$store.user.login(this.memberModel.memberInfo, '普通').then(async (msg) => {
          await this.$toast(msg, { type: 'success' })
          this.handleSuccess()
        }).catch(async (data) => {
          await this.$toast(data, { type: 'error' })
          this.getCaptchaData()
        })
      }
      else if (this.loginType == '手机') {
        this.$refs.uForm.validateField('memberInfo.username')
        if (this.memberModel.memberInfo.username == '') {
          return
        }
        await this.$store.user.login({ phoneNumber: this.memberModel.memberInfo.username, captcha: this.memberModel.memberInfo.captcha },
          '手机').then(async (msg) => {
          await this.$toast(msg, { type: 'success' })
          this.handleSuccess()
        }).catch(async (data) => {
          await this.$toast(data, { type: 'error' })
        })
      }
      else {
        this.$refs.uForm.validateField('memberInfo.username')
        if (this.memberModel.memberInfo.username == '') {
          return
        }
        await this.$store.user.login({ email: this.memberModel.memberInfo.username, captcha: this.memberModel.memberInfo.captcha },
          '邮箱').then(async (msg) => {
          await this.$toast(msg, { type: 'success' })
          this.handleSuccess()
        }).catch(async (data) => {
          await this.$toast(data, { type: 'error' })
        })
      }
    },
    async handleSuccess() {
      const redirect = this.$Route.query.redirect
      if (redirect) {
        this.$Router.replaceAll(JSON.parse(redirect))
      }
      else {
        this.$Router.replaceAll('/')
      }
    },
    openRegisterPage() {
      this.$Router.push({
        path: '/register',
      })
    },
    async weixinLogin() {
      const userStore = this.$store.user
      uni.login({
        provider: 'weixin',
        async success(loginResp) {
          // 登录成功
          if (loginResp.errMsg == 'login:ok') {
            await userStore.loginByWechatMini(loginResp.code)
          }
        },
        fail(err) {
        // 登录授权失败
        // err.code是错误码
          console.log(err)
          this.$toast('登录失败')
        },
      })
    },
  },
}
</script>

<template>
  <view class="bg-white h-full overflow-hidden pt-12">
    <view class="mt-4">
      <image src="/static/logo.png" alt="" class="w-20 h-20 block mx-auto" />
      <view class="text-2xl text-center mt-4 font-bold">
        {{ appName }}
      </view>
    </view>
    <view class="px-20 mt-8">
      <u-radio-group
        v-model="loginType"
        placement="row"
      >
        <u-radio
          v-for="(item, index) in loginTypeList"
          :key="index"
          :custom-style="{ marginBottom: '8px' }"
          :label="item.name"
          :name="item.name"
          active-color="#fc2c2c"
          class="pl-2"
          :disabled="item.disabled"
        >
        </u-radio>
      </u-radio-group>
      <u-form
        ref="uForm"
        :model="memberModel"
        :rules="rules"
      >
        <u-form-item
          prop="memberInfo.username"
        >
          <u-input
            v-model="memberModel.memberInfo.username"
            :placeholder="getPlaceholder"
            border="surround"
          ></u-input>
        </u-form-item>
        <u-form-item
          v-if="loginType !== '普通'"
          prop="memberInfo.captcha"
        >
          <u-input
            v-model="memberModel.memberInfo.captcha"
            placeholder="请输入验证码"
            border="surround"
          >
            <template #suffix>
              <u-code
                ref="uCode"
                seconds="20"
                start-text="发送验证码"
                change-text="XS获取"
                @change="codeChange"
              ></u-code>
              <u-button
                :text="tips"
                type="success"
                size="small"
                @tap="getCode"
              ></u-button>
            </template>
          </u-input>
        </u-form-item>

        <u-form-item
          v-if="loginType === '普通'"
          prop="memberInfo.password"
        >
          <u-input
            v-model="memberModel.memberInfo.password"
            placeholder="请输入密码"
            border="surround"
            type="password"
          ></u-input>
        </u-form-item>
        <u-form-item
          v-if="loginType === '普通'"
          prop="memberInfo.captcha"
        >
          <u-input
            v-model="memberModel.memberInfo.captcha"
            placeholder="请输入验证码"
            border="surround"
          >
            <template #suffix>
              <u-image v-model:src="imgSrc" width="90" height="30"></u-image>
            </template>
          </u-input>
        </u-form-item>
        <view class="pt-2">
          <u-button type="success" @click="handleLogin">
            登录
          </u-button>
        </view>
      </u-form>
      <view class="pt-4">
        <u-button type="primary" @click="openRegisterPage">
          注册
        </u-button>
      </view>
      <view class="pt-4">
        <u-button type="warning" @click="weixinLogin">
          微信登录
        </u-button>
      </view>
      <view
        class="absolute inset-x-0 bottom-0 text-center mb-4 text-gray-400 text-sm"
      >
        <view>
          Powered by Simple Admin
        </view>
      </view>
    </view>
  </view>
</template>

<style></style>
